﻿using System.Web;
using System.IO;
using System;
using System.Configuration;
using System.Web.SessionState;

using LDAP.Web;
using LDAP.Utility;
using LDAP.Entity;
using LDAP.BLL;

namespace LDAP.Handler
{
    public class UploadHandler : BaseWebHandler, IHttpHandler, IRequiresSessionState
    {
        public new void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            switch (Action)
            {
                case "uploadFile":
                    UploadFile();
                    break;
            }

            context.Response.End();
        }
        
        /// <summary>
        /// 上传文件
        /// </summary>
        private void UploadFile()
        {
            JsonTransfer jt = new JsonTransfer();
            try
            {
                string fileName = Request.Files[0].FileName;
                string mimeType = fileName.Substring(fileName.LastIndexOf("."));
                int targetType = Tools.Web.Request.GetFormInt("targetType", 0);
                int fileSize = Request.Files[0].ContentLength;

                int maxSize = Convert.ToInt32(ConfigurationManager.AppSettings["attachment_upload_maxsize"]);
                string allowType = ConfigurationManager.AppSettings["attachment_upload_type"].ToString();
                string path = ConfigurationManager.AppSettings["attachment_upload_path"].ToString();

                if (fileSize > maxSize)
                {
                    jt.SetApiFailed("当前文件大小为：" + fileSize + "字节，超出系统最大可上传字节数：" + maxSize + "字节");
                    Response.Write(jt);
                    return;
                }
                if (!allowType.Contains("|" + mimeType.ToLower() + "|"))
                {
                    jt.SetApiFailed("当前文件类型为：" + mimeType + "，系统允许上传文件类型有：" + allowType);
                    Response.Write(jt);
                    return;
                }
                DateTime now = DateTime.Now;
                string directory = path + "/form/" + now.Year + "/" + now.Month + "/" + now.Day + "/";
                string filePath = HttpContext.Current.Server.MapPath(directory);
                if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(filePath);
                }
                string saveName = Guid.NewGuid() + mimeType;
                Request.Files[0].SaveAs(filePath + saveName);

                Attachment attachment = new Attachment
                {
                    Path = directory + saveName,
                    UserId = CurrentUser.Id,
                    UserName = CurrentUser.UserName,
                    TargetType = targetType,
                    CreateTime = now,
                    Status = 0,
                    FileName = fileName
                };
                jt.Add("id", BizAttachment.Add(attachment));
                jt.SetApiSuccess();
                jt.Add("url", ConfigurationManager.AppSettings["StaticDomain"] + directory + saveName);
            }
            catch (Exception ex)
            {
                jt.SetApiFailed(ex.Message);
            }
            Response.Write(jt);
        }
    }
}